/**
 * @project name:crm
 */
package com.yunbo.crm.service.impl;

import com.yunbo.crm.base.BaseServiceImpl;
import com.yunbo.crm.dao.RoleMapper;
import com.yunbo.crm.pojo.Role;
import com.yunbo.crm.service.RoleService;
import com.yunbo.crm.utils.AssertUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Author : yun&bo
 * @CreateDate : ==>2021/1/26 16:36
 * @ClassName : ==>
 * @Description : ==>
 * @Version
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role, Integer> implements RoleService {
    @Resource
    private RoleMapper roleMapper;

    /**
     * 添加角色的方法
     * 角色名称
     * 角色备注
     * 角色创建时间
     * 角色创建人
     *
     * @param role
     * @param request
     */
    @Override
    public void saveRole(Role role, HttpServletRequest request) {
        checkRoleParam(role);
        Role item = roleMapper.selectByRoleName(role);
        AssertUtil.isTrue(null != item, "角色已存在");
        role.setCreateBy(getLoginUserName(request));
        role.setActiveFlag(1);
        role.setCreateDate(new Date());
        role.setUpdateDate(new Date());
        role.setUpdateBy(getLoginUserName(request));
        AssertUtil.isTrue(insertSelective(role) < 1, "角色添加失败");
    }

    /**
     * 更新角色，先检查角色rowId在与否
     * 再检测是否有重名的
     * 没有就更新
     *
     * @param role
     * @param request
     */
    @Override
    public void updateRole(Role role, HttpServletRequest request) {
        AssertUtil.isTrue(role.getRowId() == null, "待修改记录不存在");
        checkRoleParam(role);
        Role item = roleMapper.selectByRoleName(role);
        AssertUtil.isTrue(null != item && !item.getRowId().equals(role.getRowId()), "角色名称已存在");
        role.setUpdateDate(new Date());
        role.setUpdateBy(getLoginUserName(request));
        AssertUtil.isTrue(updateByPrimaryKeySelective(role) < 1, "角色记录更新失败");
    }

    @Override
    public void deleteRole(Integer rowId,HttpServletRequest request) {
        Role temp = selectByPrimaryKey(rowId);
        AssertUtil.isTrue(null == rowId || null == temp, "待删除的记录不存在!");
        temp.setActiveFlag(0);
        temp.setUpdateBy(getLoginUserName(request));
        AssertUtil.isTrue(updateByPrimaryKeySelective(temp) < 1, "角色记录删除失败!");
    }

    /**
     * 添加角色权限
     * @param mids
     * @param roleId
     */
    @Override
    public void addGrant(Integer[] mids, Integer roleId) {

    }

    private void checkRoleParam(Role role) {
        AssertUtil.isTrue(StringUtils.isBlank(role.getRoleName()), "用户角色名不能为空");
        AssertUtil.isTrue(StringUtils.isBlank(role.getRoleName()), "请为角色备注");
    }
}
